<?php

class HomeController extends AppController
{
    public $helpers = array('Html', 'Form');

    public $uses = array(
        'Category',
        'Page',
        'Widget'
    );

    public function index()
    {
        $pages = $this->Page->find('all', array('order' => array('Page.id')));
        $blocks = array();
        $widgets = $this->Widget->find('all');

        if (count($pages) > 0) {
            $grid = json_decode($pages[0]['Page']['grid'], true);
            if ($grid != null) {
                foreach ($grid as $element) {
                    $block = $element;
                    $compareFct = $this->create_equals($element['id_widget']);
                    $widget = array_filter($widgets, $compareFct);
                    if ($widget != null) {
                        $widget = array_values($widget)[0]['Widget'];
                        $block['widget'] = $widget;
                        $blocks[] = $block;
                    }
                }
            }

            $this->set('blocks', $blocks);
        }
        $this->set('pages', $pages);
    }

    public function view($id = null)
    {
        if (!$id) {
            throw new NotFoundException(__('Invalid post'));
        }

        $post = $this->Post->findById($id);
        if (!$post) {
            throw new NotFoundException(__('Invalid post'));
        }
        $this->set('post', $post);
    }

    private function create_equals($id = 0)
    {
        return function ($test) use ($id) {
            return $test['Widget']['id'] == $id;
        };
    }

}

?>